<template>
  <div class="broadcast-list-container">
    <div class="header">
      <h2>广播列表</h2>
      <el-button type="primary" @click="handleAdd">添加</el-button>
    </div>
    
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="id" label="id" width="80" align="center" />
      <el-table-column prop="bordCastType" label="广播类型" align="center" />
      <el-table-column prop="bed" label="床位" align="center" />
      <el-table-column prop="broadCastContent" label="广播内容" align="center" />
      <el-table-column prop="templateName" label="宣教模板" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/api/http.js'
import { useRouter } from 'vue-router'

const router = useRouter()
const tableData = ref([])

// 获取广播列表数据
const getBroadcastList = async () => {
  try {
    const res = await http.get('/api/BroadController/GetBroadManageList')
    if (res && res.data) {
      tableData.value = res.data
    } else {
      ElMessage.error('获取广播列表失败')
    }
  } catch (error) {
    console.error('获取广播列表失败', error)
    ElMessage.error('获取广播列表失败: ' + error.message)
  }
}

// 添加广播
const handleAdd = () => {
  router.push('/BroadCastManage')
}

// 编辑广播
const handleEdit = (row) => {
  router.push({
    path: '/BroadCastManageUpd',
    query: { id: row.id }
  })
}

// 删除广播
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这条广播记录吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await http.post(`/api/BroadController/DelBroadManage?id=${row.id}`)
        if (res && res.status) {
          ElMessage.success('删除成功')
          getBroadcastList() // 刷新列表
        } else {
          ElMessage.error(res?.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 组件挂载时获取数据
onMounted(() => {
  getBroadcastList()
})
</script>

<style scoped>
.broadcast-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin: 0;
}
</style>